<?php

require './config.php';

use Thenbsp\Wechat\User;
use Thenbsp\Wechat\OAuth;
use Thenbsp\Wechat\Util\Util;
use Thenbsp\Wechat\Exception\OAuthException;

// $openid = 'oWY-5jjLjo7pYUK86JPpwvcnF2Js';

/**
 * 网页授权获取用户信息
 */
$o = new OAuth(APPID, APPSECRET);

if( !isset($_GET['code']) ) {
    $o->authorize(Util::currentUrl(), 'snsapi_userinfo');
} else {

    /**
     * 根据 code 换取 accessToken
     */
    try {
        $token = $o->getAccessToken($_GET['code']);
        // echo '<pre>';
        // var_dump($token);
        // echo '</pre>';
    } catch (OAuthException $e) {
        exit($e->getMessage());
    }

    /**
     * 根据 accessToken 获取用户信息
     */
    try {
        $user = new User($token->access_token, $token->openid);
        echo '<pre>';
        // 获取用户全部信息
        print_r($user->getParams());
        // 单独获取
        // var_dump($user->openid, $user->nickname, $user->headimgurl);
        echo '</pre>';
    } catch (Exception $e) {
        exit($e->getMessage());
    }
    
}
